/**
 * 对axios进行二次封装
 */
import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
//利用axios对象的create方法，去创建axios实例（其他配置：基础路径，超时时间等）
let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});

//reques添加请求与响应拦截器
request.interceptors.request.use((config) => {
  let userStore = useUserStore();
  //config配置对象，headers
  //config中添加token
  if (userStore.token) {
    config.headers.token = userStore.token;
  }
  return config;
});
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    //失败回调
    let message =
      error.response?.message === undefined
        ? "系统异常"
        : error.response?.message;
    ElMessage({
      type: "error",
      message,
    });
    return Promise.reject(error);
  },
);

export default request;
